﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;
using System.Web.Security;

using FSViet.Survey.Helpers;

namespace FSViet.Survey.Administration.Campaign
{
	public partial class Details : DetailsPageBase
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			CheckSite();

			if (!IsPostBack)
			{
				InitForm();
					if (ItemId != Guid.Empty)
						LoadData(ItemId);						
			}
		}

		void InitForm()
		{
			StartDateInput.Text = GlobalApplication.Now.ToString("dd/MM/yyyy hh:mm:ss tt");
		}

		void LoadData(Guid id)
		{
			TitleLabel.Text = "Update item: " + GlobalApplication.GetGuidS(id);
			try
			{
				DataHelper dataH = new DataHelper();

				var data = dataH.Load("SELECT * FROM Campaigns WHERE Id='" + GlobalApplication.GetGuidS(id) + "'", 0, 1);
				FillData(data.Rows[0]);
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString();
#endif
			}
		}

		void FillData(DataRow data)
		{
			NameInput.Text = data["Name"].ToString().Trim();
			TotalQuestionOnPageInput.Text = data["TotalQuestionOnPage"].ToString();
			if (data["Status"]!=DBNull.Value)
				StatusList.SelectedValue = data["Status"].ToString();

			MaxTimeSurveyInput.Text = data["MaxTimeSurvey"].ToString();
			CKEditorControl1.Text = data["Description"].ToString();
		}

		protected void SaveButton_Click(object sender, EventArgs e)
		{
			if (!IsValidInput()) return;

			try
			{
				DataHelper dataH = new DataHelper();
				string userId = GlobalApplication.GetGuidS((Guid)Membership.GetUser().ProviderUserKey);
				string now = GlobalApplication.NowS;

				int maxTimeToSurvey = 20;
				if (MaxTimeSurveyInput.Text.Trim().Length > 0)
					maxTimeToSurvey = Convert.ToInt32(MaxTimeSurveyInput.Text);

				int totalQuestionOnPage = 0;
				if (TotalQuestionOnPageInput.Text.Trim().Length > 0)
					totalQuestionOnPage = Convert.ToInt32(TotalQuestionOnPageInput.Text);

				if (ItemId == Guid.Empty)
				{
					dataH.Execute("INSERT INTO Campaigns(Id, Name, Description, SiteId, Status, MaxTimeSurvey, TotalQuestionOnPage, Created, CreatedId, Modified, ModifiedId) VALUES(@Id, @Name, @Description,  @SiteId, @Status, @MaxTimeSurvey, @TotalQuestionOnPage, @Created, @CreatedId, @Modified, @ModifiedId)",
						dataH.CreateParam("Id", SqlDbType.Char, GlobalApplication.GuidS),
						dataH.CreateParam("Name", SqlDbType.NVarChar, NameInput.Text.Trim()),
						dataH.CreateParam("Description", SqlDbType.NText, CKEditorControl1.Text.Trim()),
						dataH.CreateParam("SiteId", SqlDbType.Char, GlobalApplication.GetGuidS(SiteId)),
						dataH.CreateParam("Status", SqlDbType.Int, Convert.ToInt32(StatusList.SelectedValue)),
						dataH.CreateParam("MaxTimeSurvey", SqlDbType.Int, maxTimeToSurvey),
						dataH.CreateParam("TotalQuestionOnPage", SqlDbType.Int, totalQuestionOnPage),
						dataH.CreateParam("Created", SqlDbType.Char, now),
						dataH.CreateParam("CreatedId", SqlDbType.Char, userId),
						dataH.CreateParam("Modified", SqlDbType.Char, now),
						dataH.CreateParam("ModifiedId", SqlDbType.Char, userId));
				}

				else
				{
					dataH.Execute("UPDATE Campaigns SET Name=@Name, Description=@Description, Status=@Status, MaxTimeSurvey=@MaxTimeSurvey, TotalQuestionOnPage=@TotalQuestionOnPage, Modified=@Modified, ModifiedId=@ModifiedId WHERE Id=@Id",
						dataH.CreateParam("Id", SqlDbType.Char, GlobalApplication.GetGuidS(ItemId)),
						dataH.CreateParam("Name", SqlDbType.NVarChar, NameInput.Text.Trim()),
						dataH.CreateParam("Description", SqlDbType.NText, CKEditorControl1.Text.Trim()),
						dataH.CreateParam("Status", SqlDbType.Int, Convert.ToInt32(StatusList.SelectedValue)),
						dataH.CreateParam("MaxTimeSurvey", SqlDbType.Int, maxTimeToSurvey),
						dataH.CreateParam("TotalQuestionOnPage", SqlDbType.Int, totalQuestionOnPage),
						dataH.CreateParam("Modified", SqlDbType.Char, now),
						dataH.CreateParam("ModifiedId", SqlDbType.Char, userId));
				}

					Response.Redirect("List.aspx");
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString();
#endif
			}
		}

		bool IsValidInput()
		{
			bool result = true;

			if (NameInput.Text.Trim().Length < 1)
			{
				result = false;
				msg.Text = "Please enter name";
			}

			if (result)
			if (MaxTimeSurveyInput.Text.Trim().Length > 0)
			{
				int totalQuestionOnPage = 0;
				try
				{
					totalQuestionOnPage = Convert.ToInt32(MaxTimeSurveyInput.Text);
				}
				catch (Exception ex)
				{
					msg.Text = "Max time to survey is invalid";
					result = false;
				}

				if (result)
					if (totalQuestionOnPage < 0)
					{
						msg.Text = "Max time to survey must be great than 0";
						result = false;
					}
			}

			if (result)
			if (TotalQuestionOnPageInput.Text.Trim().Length > 0)
			{
				int totalQuestionOnPage = 0;
				try
				{
					totalQuestionOnPage = Convert.ToInt32(TotalQuestionOnPageInput.Text);
				}
				catch (Exception ex)
				{
					msg.Text = "Total question on page is invalid";
					result = false;
				}

				if (result)
					if (totalQuestionOnPage < 0)
					{
						msg.Text = "Total question on page must be great than 0";
						result = false;
					}
			}

			return result;
		}

		protected void DeleteButton_Click(object sender, EventArgs e)
		{
			try
			{
				Guid id = GlobalApplication.GetGuid(Request.QueryString["Id"]);
				var dataH = new DataHelper();
				if (id != Guid.Empty)
				{
					var conn = dataH.CreateConnection();
					conn.Open();
					var cmd = conn.CreateCommand();
					var trans = conn.BeginTransaction();
					cmd.Transaction = trans;
					try
					{
						cmd.CommandText = "DELETE FROM Answers WHERE CampaignId='" + GlobalApplication.GetGuidS(id) + "'";
						cmd.ExecuteNonQuery();

						cmd.CommandText = "DELETE FROM Questionư WHERE CampaignId='" + GlobalApplication.GetGuidS(id) + "'";
						cmd.ExecuteNonQuery();

						cmd.CommandText = "DELETE FROM Campaigns WHERE Id='" + GlobalApplication.GetGuidS(id) + "'";
						cmd.ExecuteNonQuery();

						trans.Commit();
					}
					catch
					{
						trans.Rollback();
						throw;
					}
					finally
					{
						conn.Close();
					}
				}

				//return to list
				if (Request.QueryString["pr"] != null)
					Response.Redirect("List.aspx?Id=" + Request.QueryString["pr"] + "&p=" + (Request.QueryString["p"] ?? "0"));
				else
					Response.Redirect("List.aspx");
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString();
#endif
			}
		}
	}
}